//
//  WPViewController.m
//  web_connect_photo
//
//  Created by endorand on 11. 12. 12..
//  Copyright (c) 2011년 __MyCompanyName__. All rights reserved.
//

#import "WPViewController.h"
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "HTTPLogging.h"
#import "DataManager.h"
#include <ifaddrs.h>
#include <arpa/inet.h>

@implementation WPViewController

static const int ddLogLevel = LOG_LEVEL_VERBOSE;
static const int httpLogLevel = HTTP_LOG_LEVEL_OFF;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
	
	[self startWebServer];
	[self initAssets];
}

-(void) initAssets
{
    NSMutableArray* arrAsset = [[DataManager sharedManager] allAsset];
    if ( arrAsset != nil )
        [arrAsset removeAllObjects];
    
    NSMutableDictionary* dicAsset = [[DataManager sharedManager] allAssetDic];
    if ( dicAsset != nil )
        [dicAsset removeAllObjects];

    if ( library != nil )
        library = nil;
    
	library = [[ALAssetsLibrary alloc] init];
	
	void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
    {
        if(result != nil)
        {
            [arrAsset addObject:result];
            [dicAsset setValue:result forKey:[[[result defaultRepresentation] url] absoluteString] ];
            
            NSLog(@"url(%@)", [[[result defaultRepresentation] url]  absoluteString]);
        }
    };
	
    void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if( group != nil )
        {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }
		else
		{
			[self initNotice];
			[self initAssetsToWeb];
		}
    };
	
    void (^assetFailureBlock)(NSError *) = ^(NSError *error)
    {
		NSLog(@"assetFailureBlock");
    };
	
	[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
}


-(void) startWebServer
{
	[self stopWebServer];
    
	[DDLog addLogger:[DDTTYLogger sharedInstance]];
	
	httpServer = [[HTTPServer alloc] init];
	[httpServer setType:@"_http."];
	
    NSString* webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"web"];
    [httpServer setDocumentRoot:webPath];
    
    // port
    [httpServer setPort:12345];
    
	// set port & start
	NSError* error = nil;
    if ( [httpServer start:&error] )
    {
        NSLog(@"server port(%d)", httpServer.listeningPort);
    }
}

-(void) initAssetsToWeb
{
	// set to web
}

-(void)stopWebServer
{
	if ( httpServer != nil )
	{
		[httpServer stop];
		httpServer = nil;
	}
}

-(void) initNotice
{
	NSString* t = [NSString stringWithString:@"Local Web Server initiated.\n"];
	t = [t stringByAppendingFormat:@"URL : http://%@:%d\n", [self getIPAddress], httpServer.listeningPort];
	
	tvNotice = [[UITextView alloc] initWithFrame:self.view.frame];
	tvNotice.userInteractionEnabled = NO;
	tvNotice.backgroundColor = [UIColor clearColor];
	tvNotice.font = [UIFont boldSystemFontOfSize:20.0f];
	tvNotice.text = t;
	[self.view addSubview:tvNotice];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
